#_*_ coding: UTF-8 _*_

from core import uicomponents, db, log
from PyQt4 import QtGui, QtCore
from servers.title.definitions import *

class TitleTree(QtGui.QTreeWidget):
	def __init__(self,parent=None,mw=None):
		QtGui.QTreeWidget.__init__(self,parent)
		self.setFont(uicomponents.SharedUi.defaultFont)
		self.setMinimumWidth(50)
		self.setColumnCount(1)

		self.createActions()
		
		self.setAcceptDrops(False)
		self.setDragEnabled(False)
		self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
		self.setDropIndicatorShown(False)
		self.mw = mw
	
	def createActions(self):
		self.delAct = QtGui.QAction(u"&حذف", self)
		self.delAct.setShortcut(self.tr("Ctrl+d"))
		self.connect(self.delAct, QtCore.SIGNAL("triggered()"), self.deleteCurrent)

		self.insAct = QtGui.QAction(u"&اضافه", self)
		self.insAct.setShortcut(self.tr("Ctrl+f"))
		self.connect(self.insAct, QtCore.SIGNAL("triggered()"), self.insertAfter)

		self.insChildAct = QtGui.QAction(u"&زير عنوان جديد", self)
		self.insChildAct.setShortcut(self.tr("Ctrl+g"))
		self.connect(self.insChildAct, QtCore.SIGNAL("triggered()"), self.insertChild)

		self.renameAct = QtGui.QAction(u"&تغيير عنوان", self)
		self.renameAct.setShortcut(self.tr("Ctrl+h"))
		self.connect(self.renameAct, QtCore.SIGNAL("triggered()"), self.renameTitle)

		self.cutAct = QtGui.QAction(u"&انتقال از",self)
		self.cutAct.setShortcut(self.tr("Ctrl+x"))
		self.connect(self.cutAct,QtCore.SIGNAL("triggered()"),self.cutTitle)

		self.pasteAct = QtGui.QAction(u"&انتقال به",self)
		self.pasteAct.setShortcut(self.tr("Ctrl+v"))
		self.connect(self.pasteAct,QtCore.SIGNAL("triggered()"),self.pasteTitle)


		self.cmenu = QtGui.QMenu(self)
		self.cmenu.addAction(self.delAct)
		self.cmenu.addAction(self.insAct)
		self.cmenu.addAction(self.insChildAct)
		self.cmenu.addAction(self.renameAct)
		self.cmenu.addAction(self.cutAct)
		self.cmenu.addAction(self.pasteAct)


		QtCore.QObject.connect(self,QtCore.SIGNAL("itemSelectionChanged()"),self.titleSelected)

        def titleSelected(self):
		s = " "
		try:
	                s = self.sections[list(self.selectedItems())[0]]	
			f = open(s.file_path(),"rb")
			lines = f.readlines()
			f.close()
			st = u"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body dir=rtl>" + "".join(lines);
			sectionComment.sectionEditor.setHtml(st)
			uicomponents.SharedUi.applications['title']['docables']['titleComment'].setWindowTitle(s.name)
		except:
			sectionComment.sectionEditor.clear()
			uicomponents.SharedUi.applications['title']['docables']['titleComment'].setWindowTitle(s.name)

	
	def cutTitle(self):
		self.cuttedItem = self.sections[list(self.selectedItems())[0]]
	
	def pasteTitle(self):
		metadata.engine.echo = True
		if self.cuttedItem != None :
			s = self.sections[list(self.selectedItems())[0]]
			db.connect().execute("update section set _index=_index+1 where parent_id=%d and _index>%d" % (s.parent_id,s._index))
			self.cuttedItem.parent_id = s.parent_id
			self.cuttedItem._index = s._index + 1
			session.flush()
			reloadTree()
			self.fillTree()
			self.cuttedItem = None
		metadata.engine.echo = False	

	def deleteCurrent(self):
		s = self.sections[list(self.selectedItems())[0]]	
		if s.parent_id==102:
			s.parent_id = -1
		else:
			s.parent_id = 102
		session.flush()
		reloadTree()
		self.fillTree()


	def insertAfter(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = "%s" % x[0]
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]	
			db.connect().execute("update section set _index=_index+1 where parent_id=%d and _index>%d" % (s.parent_id,s._index))
			se = Section()
			se._index=s._index+1
			se.parent_id=s.parent_id
			se.name=newName
			session.save(se)
			session.flush()
			reloadTree()
			self.fillTree()

	def insertChild(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = "%s" % x[0]
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]	
			db.connect().execute("update section set _index=_index+1 where parent_id=%d " % s.parent_id)
			se = Section()
			se._index=0
			se.parent_id=s.id
			se.name=newName
			session.save(se)
			session.flush()
			reloadTree()
			self.fillTree()


	def renameTitle(self):
		answer = False
		x = QtGui.QInputDialog.getText(self,u"نام عنوان جديد",u"عنوان جديد:")
		newName = unicode("%s" % x[0])
		answer = x[1]
		if(answer):
			s = self.sections[list(self.selectedItems())[0]]
			s.name = newName
			session.flush()
			reloadTree()
			self.fillTree()


	def contextMenuEvent(self,event):
		self.cmenu.exec_(event.globalPos())
	
	def addSectionChilds(self,si,qtwi):
		for s in si.childs:
			tqtwi = QtGui.QTreeWidgetItem(qtwi)
			self.sections[tqtwi] = s
			tqtwi.setText(0,s.name)
			self.addSectionChilds(s,tqtwi)
	
	def treeEntered(self,q,i):
		print "tree enter"
		print q
		print i

	def fillTree(self):
		self.clear()
		reloadTree()
		try:
			del self.sections
		except:
			pass
		self.sections = {}

		for sec in section_query.select(Section.c.parent_id==-1,order_by=[Section.c.parent_id,Section.c._index]):
			tqtwi = QtGui.QTreeWidgetItem(self)			
			self.sections[tqtwi] = sec
			tqtwi.setText(0,sec.name)
			self.addSectionChilds(sec,tqtwi)
		
#		tqtwi = QtGui.QTreeWidgetItem(self)
#		self.sections[tqtwi] = self.mw.recycle
#		tqtwi.setText(0,self.mw.recycle.name)
#		self.addSectionChilds(self.mw.recycle,tqtwi)


class SectionEditor(QtGui.QTextBrowser):
	def __init__(self,parent=None,mw=None):
		QtGui.QTextBrowser.__init__(self,parent)
		self.setReadOnly(False)
		self.mw = mw


class SectionComment(QtGui.QFrame):
	def __init__(self,parent=None):
		QtGui.QFrame.__init__(self,parent)
		self.setFont(uicomponents.SharedUi.defaultFont)
		self.sectionEditor = SectionEditor(parent=self)
		self.controlToolBar = QtGui.QToolBar()
		self.controlToolBar.setMaximumHeight(40)

		self.boldAction = QtGui.QAction(QtGui.QIcon(QtGui.QPixmap("images/bold.png")),"Bold",self.controlToolBar)
		self.boldAction.setShortcut('Ctrl+B')
		self.connect(self.boldAction,QtCore.SIGNAL("triggered()"),self.boldSelection)

		self.saveAction = QtGui.QAction(QtGui.QIcon(QtGui.QPixmap("images/save.png")),"Save",self.controlToolBar)
		self.saveAction.setShortcut('Ctrl+S')
		self.connect(self.saveAction,QtCore.SIGNAL("triggered()"),self.saveDocument)


		self.controlToolBar.addAction(self.boldAction)
		self.controlToolBar.addAction(self.saveAction)

		self.mlayout = QtGui.QVBoxLayout()
		self.mlayout.addWidget(self.controlToolBar)		
		self.mlayout.addWidget(self.sectionEditor)

		self.setLayout(self.mlayout)

	def saveDocument(self):
		f = QtCore.QFile(titles.sections[list(titles.selectedItems())[0]].file_path())
		f.open(QtCore.QIODevice.WriteOnly)
		f.write(self.sectionEditor.toHtml().toUtf8())
		f.close()


	def boldSelection(self):
		a = self.sectionEditor.currentCharFormat()
		if a.fontWeight() == QtGui.QFont.Black :
			a.setFontWeight(QtGui.QFont.Normal)
		else:	
			a.setFontWeight(QtGui.QFont.Black)	
		self.sectionEditor.setCurrentCharFormat(a)

		a = self.sectionEditor.textCursor().charFormat()
		if a.fontWeight() == QtGui.QFont.Black :
			a.setFontWeight(QtGui.QFont.Normal)
		else:	
			a.setFontWeight(QtGui.QFont.Black)	
		self.sectionEditor.textCursor().setCharFormat(a)



recyle = None
rootTitle = None

def reloadTree():
	
	#session.clear()
	#session.close()
	#section_query = session.query(Section)
	#document_query = session.query(Document)
	#documentTitle_query = session.query(DocumentTitle)

        try:
            recycle = section_query.select(Section.c.id==102,order_by=[Section.c.parent_id,Section.c._index])[0]
        except:
		log.logger.error('Problem in finding recycle,create one...')
		recycle = Section()
		recycle.id = 102
		recycle.parent_id = -1
		recycle.name=u'پاک شده ها'
		recycle.index = 100
		session.save(recycle)
		session.flush()

	try:
		rootTitle = section_query.select(Section.c.id==104,order_by=[Section.c.parent_id,Section.c._index])[0]
	except:
	    log.logger.error('Problem in finding jalasat root,create one...')	
            rootTitle = Section()
	    rootTitle.id = 104
	    rootTitle.parent_id = -1
	    rootTitle.name=u'عناوين جلسات'
	    rootTitle.index = 10
	    session.save(rootTitle)
	    session.flush()



def showView():
	uicomponents.SharedUi.mainWindow.addDockWidget(QtCore.Qt.LeftDockWidgetArea,uicomponents.SharedUi.applications['title']['docables']['titleTree'])
	uicomponents.SharedUi.applications['title']['docables']['titleTree'].show()
	uicomponents.SharedUi.mainWindow.addDockWidget(QtCore.Qt.RightDockWidgetArea,uicomponents.SharedUi.applications['title']['docables']['titleComment'])
	uicomponents.SharedUi.applications['title']['docables']['titleComment'].show()



uicomponents.SharedUi.applications['title']  = {}
uicomponents.SharedUi.applications['title']['actionSlot'] = showView
uicomponents.SharedUi.applications['title']['name']  = u'عناوين'
uicomponents.SharedUi.applications['title']['shortcut'] = u'Ctrl+W'
uicomponents.SharedUi.applications['title']['docables']={}
uicomponents.SharedUi.applications['title']['docables']['titleComment'] = QtGui.QDockWidget(uicomponents.SharedUi.mainWindow)
uicomponents.SharedUi.applications['title']['docables']['titleComment'].setWindowTitle(u'توضيح عناوين')
uicomponents.SharedUi.applications['title']['docables']['titleComment'].resize(500,100)
sectionComment = SectionComment()
uicomponents.SharedUi.applications['title']['docables']['titleComment'].setWidget(sectionComment)
uicomponents.SharedUi.applications['title']['docables']['titleComment'].hide()

uicomponents.SharedUi.applications['title']['docables']['titleTree'] = QtGui.QDockWidget(uicomponents.SharedUi.mainWindow)
uicomponents.SharedUi.applications['title']['docables']['titleTree'].setWindowTitle(u'درخت عناوين')
titles = TitleTree()
uicomponents.SharedUi.applications['title']['docables']['titleTree'].setWidget(titles)
uicomponents.SharedUi.applications['title']['docables']['titleTree'].hide()
titles.fillTree()


print "Title Ui Components Added"
